﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.IO;
using System.Text;

using AKMII.DMRA.Business.Service;
using AKMII.DMRA.Business.Rule;
using AKMII.DMRA.Common;
using AKMII.DMRA.DataAccess;

namespace AKMII.DMRA.Business.Management
{
    public class ReportManager
    {
        private OrderAccessor orderAccessor;

        public ReportManager()
        {
            orderAccessor = new OrderAccessor();
        }

        public void SendReport(string id, int month, int year)
        {
            try
            {
                Mail mail = new Mail();
                //mail.AttachmentFile = path;
                mail.Subject = string.Format(Constants.SubjectForOrderMail,
                    Utility.GetNumber(month), Utility.GetNumber(year));
                mail.Content = string.Format(Constants.ContentForSummaryMail,
                    Utility.GetNumber(month), Utility.GetNumber(year));
                mail.Recipients = new List<string>() { new AccountManager().GetMailAddress(id) };

                SmtpMailService mailService = new SmtpMailService(SystemConfiguration.CommonSetting.SmtpServer,
                    SystemConfiguration.CommonSetting.SystemMailAddress, SystemConfiguration.CommonSetting.MailPassword);
                mailService.Send(mail);
                /*
                LeadManager lm = new LeadManager();

                List<Lead> leads = lm.GetLeads(id, month, year);

                List<string> territories = new List<string>();
                territories = leads.OrderBy(c => c.Territory).Select(c => c.Territory).Distinct().ToList<string>();

                List<Lead> leadByTerritory = new List<Lead>();
                foreach (string territory in territories)
                {
                    leadByTerritory = leads.OrderBy(c => c.LeadBlockCode).Where(c => c.Territory == territory).Select(c => c).ToList<Lead>();
                    GenerateReport(leadByTerritory, territory, id, month, year);
                    leadByTerritory.Clear();
                }

                ZipAccessor accessor = new ZipAccessor();

                List<LeadBlock> codes = accessor.GetLeadBlock(id, month, year);
                GenerateReport(codes, id, month, year);
                 * */
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occurs in send report", ex);
            }
        }

        public void SendReport(string id, int month, int year, int type)
        {
            AccountManager am = new AccountManager();
            List<string> fileNames = GetReport(id, month, year, type);

            foreach (var fileName in fileNames)
            {
                Mail mail = new Mail();
                mail.AttachmentFile = fileName;
                mail.Subject = string.Format(Constants.SubjectForOrderMail,
                    Utility.GetNumber(month), Utility.GetNumber(year));
                if (fileName.Contains("_DetailRpt"))
                {
                    mail.Content = string.Format(Constants.ContentForOrderMail,
                        Utility.GetNumber(month), Utility.GetNumber(year));
                }
                else
                {
                    mail.Content = string.Format(Constants.ContentForSummaryMail,
                        Utility.GetNumber(month), Utility.GetNumber(year));
                }
                mail.Recipients = new List<string>() { am.GetMailAddress(id) };

                SmtpMailService mailService = new SmtpMailService(SystemConfiguration.CommonSetting.SmtpServer,
                    SystemConfiguration.CommonSetting.SystemMailAddress, SystemConfiguration.CommonSetting.MailPassword);
                mailService.Send(mail);
            }
        }

        public int CheckReport(string id, int month, int year, int type)
        {
            int result = 0;

            try
            {
                if (GetReport(id, month, year, type).Count > 0)
                {
                    result = 1;
                }
                else
                {
                    Order order = orderAccessor.GetOrderByIdAndDate(id, month, year);
                    if (order != null && order.IsPurchased)
                    {
                        result = 2;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occurs in checking report,", ex);
            }


            return result;
        }

        private void GenerateReport(List<Lead> leadsPool, string territory, string id, int month, int year)
        {
            AccountManager am = new AccountManager();
            string path = Path.Combine(Constants.ExcelReportPath,
                                   string.Format(Constants.FileNameForOrder, id, "Ter" + territory,
                                   Utility.GetNumber(month), Utility.GetNumber(year)));

            ExcelReportService excelService = new ExcelReportService();
            SetDefaultPrinter();
            excelService.GenerateReport(path, leadsPool, leadsPool.Select(c => c.LeadBlockCode).Distinct().ToList<string>(), true);

            Mail mail = new Mail();
            mail.AttachmentFile = path;
            mail.Subject = string.Format(Constants.SubjectForOrderMail,
                Utility.GetNumber(month), Utility.GetNumber(year));
            mail.Content = string.Format(Constants.ContentForOrderMail,
                Utility.GetNumber(month), Utility.GetNumber(year));
            mail.Recipients = new List<string>() { am.GetMailAddress(id) };

            SmtpMailService mailService = new SmtpMailService(SystemConfiguration.CommonSetting.SmtpServer,
                SystemConfiguration.CommonSetting.SystemMailAddress, SystemConfiguration.CommonSetting.MailPassword);
            mailService.Send(mail);
        }

        public void GenerateReport(List<LeadBlock> codes, string id, int month, int year)
        {
            AccountManager am = new AccountManager();
            string path = Path.Combine(Constants.ExcelReportPath,
                                   string.Format(Constants.FileNameForSummaryOrder, id, Utility.GetNumber(month), Utility.GetNumber(year)));

            ExcelReportService excelService = new ExcelReportService();
            SetDefaultPrinter();
            excelService.GenerateReport(path, codes);

            //Mail mail = new Mail();
            //mail.AttachmentFile = path;
            //mail.Subject = string.Format(Constants.SubjectForOrderMail,
            //    Utility.GetNumber(month), Utility.GetNumber(year));
            //mail.Content = string.Format(Constants.ContentForSummaryMail,
            //    Utility.GetNumber(month), Utility.GetNumber(year));
            //mail.Recipients = new List<string>() { am.GetMailAddress(id) };

            //SmtpMailService mailService = new SmtpMailService(SystemConfiguration.CommonSetting.SmtpServer,
            //    SystemConfiguration.CommonSetting.SystemMailAddress, SystemConfiguration.CommonSetting.MailPassword);
            //mailService.Send(mail);
        }

        private void SetDefaultPrinter()
        {
            try
            {
                ManagementObjectSearcher query;
                ManagementObjectCollection queryCollection;

                query = new ManagementObjectSearcher(Constants.ClassName);
                queryCollection = query.Get();

                foreach (ManagementObject mo in queryCollection)
                {
                    if (mo["Name"].ToString() == Constants.PrinterName)
                    {
                        mo.InvokeMethod(Constants.CommandOfSetDefaultPrinter, new object[] { mo["Name"] });
                        Logger.Info("Set default printer to " + Constants.PrinterName);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occurs in set default printer", ex);
            }
        }

        private List<string> GetReport(string id, int month, int year, int type)
        {
            List<string> files = new List<string>();
            files.AddRange(Directory.GetFiles(Constants.ExcelReportPath, "*.xlsx"));
            files.AddRange(Directory.GetFiles(Constants.ExcelReportPath, "*.xls"));

            List<string> fileNames = new List<string>();

            switch (type)
            {
                case 0:
                    fileNames = files.Where(c => c.ToUpper().Contains(id.ToUpper()) 
                        && c.Contains(Utility.GetNumber(month) + Utility.GetNumber(year))).ToList<string>();
                    break;
                case 1:
                    fileNames = files.Where(c => c.ToUpper().Contains(id.ToUpper()) 
                        && c.Contains(Utility.GetNumber(month) + Utility.GetNumber(year) + "_DetailRpt")).ToList<string>();
                    break;
                case 2:
                    fileNames = files.Where(c => c.ToUpper().Contains(string.Format(Constants.FileNameForSummaryOrder.ToUpper(), id.ToUpper(), Utility.GetNumber(month), Utility.GetNumber(year)))).ToList<string>();
                    break;
                default:
                    break;
            };

            return fileNames;
        }
    }
}
